from typing import List, Dict, Optional
from scorpio.core.common import ModelParameter, MCPServerConfig 

def get_provider_model_names(model_params: List[ModelParameter]) -> Dict:
    models = {}
    for m in model_params:
        provider = m.provider
        if models.get(provider) is None:
            models[provider] = [m.model]
        else:
            models[provider].append(m.model)
    return models

def get_provider_models(model_params: List[ModelParameter]) -> Dict:
    models = {}
    for m in model_params:
        provider = m.provider
        if models.get(provider) is None:
            models[provider] = [m]
        else:
            models[provider].append(m)
    return models

def get_chosen_model_config(model_params: List[ModelParameter], 
        provider: str,
        model_name: str)->ModelParameter:
    models=get_provider_models(model_params)
    chosen_model=None
    models_cfg=models.get(provider) or None
    if models_cfg is None:
        return chosen_model
    for model_cfg in models_cfg:
        if model_cfg.model== model_name or model_cfg.title == model_name:
            chosen_model = model_cfg
            break
    if chosen_model is None:
        chosen_model = model_cfg[0]
    return chosen_model

def get_mcp_server_names(mcp_servers: Dict[str, MCPServerConfig])->List[str]:
    server_names=[]
    for name,config in mcp_servers.items():
        if config.disabled:
            continue
        server_names.append(name)
    return server_names

def get_mcp_config(mcp_servers: Dict[str, MCPServerConfig], mcp_server: str)->MCPServerConfig:
    return mcp_servers.get(mcp_server)

def get_providers_data(model_params: List[ModelParameter]) -> Dict:
    """生成供应商-模型映射数据"""
    providers = list(get_provider_models(model_params).keys())
    return providers

def parse_model_mention(text: str, models: List[Dict]) -> Optional[str]:
    """解析@符号选择的模型（修复原代码错误）"""
    if '@' in text:
        mention_part = text.split('@')[-1].split()[0]
        # 遍历实际模型列表（原代码错误使用range(models)）
        for model in models:
            # 原数据无'name'字段，改为匹配'title'或'model'
            if model.get('title') == mention_part or model.get('model') == mention_part:
                return model['model']
    return None
